package com.ruoyi.central.publisher.subscription.art.process.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.central.domain.TopCentralArtProcess;
import com.ruoyi.central.domain.TopCentralProcessStep;
import com.ruoyi.central.publisher.event.ArtProcessEvent;
import com.ruoyi.central.publisher.event.ProcessStepEvent;
import com.ruoyi.central.service.ITopCentralProcessStepService;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Classname ProcessStepSUbscriptionArtProcessEvent
 * @Author: sunluquan
 * @Date: 2022/5/19 11:02
 * @Description TODO
 * 工序对象 订阅 工艺数据发生改变事件
 */
@Component
@Order(2)
public class ProcessStepSubscriptionArtProcessEvent {

    @Autowired
    private ITopCentralProcessStepService processStepService;

    /**
     * 删除工艺事件订阅
     * @param event
     */
    @EventListener(value = ArtProcessEvent.class,condition = "#event.getSignEnum().name()=='DELETE'")
    public ProcessStepEvent deleteOfArtProcessEvent(ArtProcessEvent event){

        List<Integer> artProcessIdsOfDelete = CollectionUtils.mapToList(event.getSources(), TopCentralArtProcess::getId);

        LambdaQueryWrapper<TopCentralProcessStep> lambdaQuery = processStepService.lambdaQuery().select(TopCentralProcessStep::getId);

        if(artProcessIdsOfDelete.size()==1){
            lambdaQuery.eq(TopCentralProcessStep::getArtProcessId,CollectionUtils.getFirst(artProcessIdsOfDelete));
        }else{
            lambdaQuery.eq(TopCentralProcessStep::getArtProcessId,artProcessIdsOfDelete);
        }

        List<TopCentralProcessStep> processSteps = processStepService.selectSimpleList(lambdaQuery);
        List<Integer> processStepIds = CollectionUtils.mapToList(processSteps, TopCentralProcessStep::getId);

        if(StringUtils.isNotEmpty(processStepIds)){
            //因为是自动触发
            processStepService.getBaseMapper().deleteBatchIds(processStepIds);
            //系统内部自动发布
            return new ProcessStepEvent(processSteps,event.getSignEnum(),true);
        }
        return null;
    }
}
